// const path = require('path');
// module.exports = {

// };
const path = require('path');
const { loaderByName, addBeforeLoader } = require('@craco/craco');
const { CracoAliasPlugin, configPaths } = require('react-app-rewire-alias');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const { addLoadersForWorkersAndPackages } = require('../craco-common');
const packageRootPath = path.resolve(
  __dirname,
  '../../../amcax-renderer/packages/commons',
);
// Don't open the browser during development
//process.env.BROWSER = "none";
module.exports = {
  webpack: {
    babel: {
      plugins: [
        [
          '@locator/babel-jsx/dist',
          {
            env: 'development',
          },
        ],
      ],
    },
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
    plugins: {
      add: [
        new NodePolyfillPlugin(), // for Webpack 5
      ],
    },
    configure: (webpackConfig, { env, paths }) => {
      addBeforeLoader(webpackConfig, loaderByName('babel-loader'), {
        test: /\.(js|jsx|ts|tsx)$/,
        include: [packageRootPath],
        loader: 'babel-loader',
        options: {
          presets: [
            '@babel/preset-env',
            '@babel/preset-typescript',
            '@babel/preset-react',
          ],
        },
      });
      // // 添加对 .module.scss 文件的支持
      // const scssRule = webpackConfig.module.rules.find(
      //   (rule) => rule.test && rule.test.toString().includes('scss'),
      // );
      // if (scssRule && scssRule.oneOf) {
      //   scssRule.oneOf.forEach((rule) => {
      //     if (rule.test && rule.test.toString().includes('scss')) {
      //       rule.use = [
      //         ...rule.use,
      //         {
      //           loader: 'css-loader',
      //           options: {
      //             modules: {
      //               localIdentName: '[local]__[hash:base64:5]', // 自定义生成的类名格式
      //             },
      //             importLoaders: 2,
      //             sourceMap: true,
      //           },
      //         },
      //         'sass-loader',
      //       ];
      //       // 更新规则以匹配 .module.scss 文件
      //       rule.test = /\.module\.scss$/;
      //     }
      //   });
      // }

      // // 确保非模块化的 .scss 文件仍然被正确处理
      // webpackConfig.module.rules.push({
      //   test: /\.scss$/,
      //   exclude: /\.module\.scss$/,
      //   use: ['style-loader', 'css-loader', 'sass-loader'],
      // });

      if (!Array.isArray(webpackConfig.module.rules)) {
        webpackConfig.module.rules = [];
      }
      addLoadersForWorkersAndPackages(webpackConfig);

      webpackConfig.resolve.modules = [
        ...webpackConfig.resolve.modules,
        path.join(__dirname, 'src/modules'),
      ];
      // webpackConfig.output = {
      //   ...webpackConfig.output,
      //   filename: 'static/js/[name].[contenthash:8].js',
      //   chunkFilename: 'static/js/[name].[contenthash:8].chunk.js',
      // };
      webpackConfig.externals = {
        ...webpackConfig.externals,
        'verb-nurbs': 'verb',
      };
      webpackConfig.resolve.fallback = {
        ...webpackConfig.resolve.fallback,
        fs: false, // for winston on Webpack 5
      };
      // Work around build errors on MacOS:
      //   ERROR in ./src/app/common/scene/viewer.ts 69:6-13
      //   Module not found: Error: You attempted to import .../node_modules/console-browserify/index.js
      //   which falls outside of the project src/ directory.Relative imports outside of src/ are not supported.
      //   You can either move it inside src /, or add a symlink to it from project's node_modules/.
      // See also:
      //   * https://stackoverflow.com/questions/44114436/the-create-react-app-imports-restriction-outside-of-src-directory
      //   * [create-react-app: Relative imports outside of /src are not supported](https://github.com/bradlc/babel-plugin-tailwind-components/issues/36)
      webpackConfig.resolve.plugins = webpackConfig.resolve.plugins.filter(
        (plugin) => !(plugin instanceof ModuleScopePlugin),
      );

      process.env.NODE_ENV === 'production' &&
        (webpackConfig.output.filename = 'static/js/[name].[contenthash:8].js');
      process.env.NODE_ENV === 'production' &&
        (webpackConfig.output.chunkFilename =
          'static/js/[name].[contenthash:8].chunk.js');

      // 配置publicPath
      process.env.NODE_ENV === 'production' &&
        (webpackConfig.output.publicPath = process.env.PUBLIC_URL);

      return webpackConfig;
    },
  },
  devServer: {
    headers: {
      'Access-Control-Allow-Origin': 'http://localhost:8880',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Headers':
        'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,token',
      // 可以添加更多的headers
    },
  },
  style: {
    postcss: {
      mode: 'file',
    },
  },
  plugins: [
    {
      plugin: CracoAliasPlugin,
      options: { alias: configPaths('./tsconfig.paths.json') },
    },
  ],
};
